/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aviso.controller;

import aviso.entity.ImageFile;
import aviso.entity.UserName;
import aviso.facade.ImageFileFacade;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.imageio.ImageIO;
import org.primefaces.event.FileUploadEvent;

@ManagedBean
@ViewScoped
public class FileUploadController implements Serializable {

    @EJB
    private ImageFileFacade facade;
    private static final int BUFFER_SIZE = 6124;
    private static transient String path = "\\upload";
    private boolean showDialog = false;
    @ManagedProperty(value = "#{frontController.user}")
    private UserName userName;

    @PostConstruct
    public void init() {
        String tmp = FacesContext.getCurrentInstance().getExternalContext().getInitParameter("upload-path");
        path = tmp == null ? path : tmp;
    }

    private String printPath() {
        return path;
    }
    private Collection<ImageFile> files = null;
    private ImageFile selectedFile = null;

    public Collection<ImageFile> getFiles() {
        if (files == null && userName != null) {
            files = facade.listByUser(userName.getId());
        }
        return files;
    }
    //DUMP action

    public void refresh() {
    }

    public void refreshFiles() {
        files = facade.listByUser(userName.getId());
    }

    public void removeFile() {
        facade.remove(selectedFile);
        refreshFiles();
    }

    public void setFiles(List<ImageFile> files) {

        this.files = files;
    }

    public ImageFile getSelectedFile() {
        return selectedFile;
    }

    public void setSelectedFile(ImageFile selectedFile) {
        this.selectedFile = selectedFile;
    }

    public int getHeight() {
        return selectedFile.getHeight();
    }

    public int getWidth() {
        return selectedFile.getWidth();
    }

    public UserName getUserName() {
        return userName;
    }

    public void setUserName(UserName userName) {
        this.userName = userName;
    }

    public boolean isShowDialog() {
        return showDialog;
    }

    public void setShowDialog(boolean showDialog) {
        this.showDialog = showDialog;
    }
    
    public void showDialog() {
        this.showDialog = true;
    }
    public void hideDialog()
    {
        this.showDialog=false;
    }

    public void handleFileUpload(FileUploadEvent event) {

        ExternalContext extContext = FacesContext.getCurrentInstance().
                getExternalContext();
        File result = new File(extContext.getRealPath(path) + "//" + userName.getName() + "//" + event.getFile().getFileName());

        File dir = new File(extContext.getRealPath(path) + "//" + userName.getName());

        try {
            dir.mkdir();
            result.createNewFile();
            FileOutputStream fileOutputStream = new FileOutputStream(result);

            byte[] buffer = new byte[BUFFER_SIZE];

            int bulk;
            InputStream inputStream = event.getFile().getInputstream();
            while (true) {
                bulk = inputStream.read(buffer);
                if (bulk < 0) {
                    break;
                }
                fileOutputStream.write(buffer, 0, bulk);
                fileOutputStream.flush();
            }

            fileOutputStream.close();
            inputStream.close();
            BufferedImage bi = ImageIO.read(result);


            if (facade.getCountNameAndUser(result.getName(), userName.getId()) == 0) {
                ImageFile file = new ImageFile();
                file.setHeight(bi.getHeight());
                file.setWidth(bi.getWidth());
                file.setName(result.getName());
                file.setUserName(userName);
                facade.create(file);
                setSelectedFile(file);
            }
            
            FacesMessage msg = new FacesMessage("Succesful",
                    event.getFile().getFileName() + " is uploaded.");
            FacesContext.getCurrentInstance().addMessage(null, msg);


        } catch (IOException e) {
            e.printStackTrace();

            FacesMessage error = new FacesMessage("The files were not uploaded!");
            FacesContext.getCurrentInstance().addMessage(null, error);
        }
    }
}
